//  异常统一处理中间件
const { ValidationError } = require('sequelize')
const { CustomError } = require('../core/common')
const {ParameterError}=require("../config/errorCode")
const Exception = async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    const isCustomError = error instanceof CustomError || error instanceof ValidationError
    // 如果是开发环境并且是未知异常 则抛出异常
    if (process.env.NODE_ENV == 'development' && !isCustomError) {
      throw error
    }
    // 如果是自定义异常(已知)
    if (isCustomError) {
      if (error instanceof ValidationError) {
        ctx.body = {
          code: ParameterError,
          msg: error.errors[0].message
        }
      } else {
        ctx.body = error
      }
    }
    // 如果是生产环境并且是未知异常
    else {
      ctx.body = {
        msg: '未知异常'
      }
      ctx.status = 500
    }
  }
}
module.exports = Exception
